package ai.people.core.plugin.listener;

import ai.people.core.plugin.utils.ManualRegisterBeanUtil;
import ai.people.core.plugin.utils.HotDeployUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;

/**
 * 文件侦听器
 *
 * @author yuanqinglong
 * @date 2022/6/13 19:06
 */
public class JarListener extends FileAlterationListenerAdaptor {

    private final Logger logger = LoggerFactory.getLogger(JarListener.class);

    private final ConfigurableApplicationContext applicationContext;

    public JarListener(ConfigurableApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 文件创建
     *
     * @param file 文件
     */
    @Override
    public void onFileCreate(File file) {
        Set<String> classNameSet = HotDeployUtils.readJarFile(file.getPath());
        ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
        for (String className : classNameSet) {
            Class<?> clazz = null;
            try (URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader())){
                if(classLoader != null){
                    clazz =classLoader.loadClass(className);
                }
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }
            if (clazz != null) {
                ManualRegisterBeanUtil.registerBean(clazz, beanFactory);
                ManualRegisterBeanUtil.hotRefreshBeanField(beanFactory);
            }
        }
    }



    /**
     * 在文件更改
     *
     * @param file 文件
     */
    @Override
    public void onFileChange(File file) {

    }


    /**
     * 在文件删除
     *
     * @param file 文件
     */
    @Override
    public void onFileDelete(File file) {

    }


    /**
     * 在目录中创建
     *
     * @param directory 目录
     */
    @Override
    public void onDirectoryCreate(File directory) {

    }

    /**
     * 目录变化
     *
     * @param directory 目录
     */
    @Override
    public void onDirectoryChange(File directory) {

    }


    /**
     * 在目录删除
     *
     * @param directory 目录
     */
    @Override
    public void onDirectoryDelete(File directory) {

    }


    /**
     * 在开始
     *
     * @param observer 观察者
     */
    @Override
    public void onStart(FileAlterationObserver observer) {

    }


    /**
     * 在停止
     *
     * @param observer 观察者
     */
    @Override
    public void onStop(FileAlterationObserver observer) {

    }

}
